<template>
  <div class="main">
    <div class="option-container" v-loading="pageLoading">
      <el-form label-width="100px" label-position="left">
        <el-form-item label="日期">
          <date-picker v-model="startDate" placeholder="请选择开始日期" :dateOptions="dateOptions"/>
          <span style="padding: 0 15px" v-show="multiDay">到</span>
          <date-picker v-model="endDate" v-show="multiDay" placeholder="请选择结束日期" :dateOptions="dateOptions"/>

          <el-button type="primary" plain @click="drawChart" v-show="chartsVisible" style="margin-left: 10px" icon="el-icon-refresh">刷新图表</el-button>
          <el-button type="danger" @click="deleteChart" v-if="singleDay && showDelete" icon="el-icon-delete">删除本图表</el-button>

        </el-form-item>
        <el-form-item label="降雨量级">
          <el-select v-model="level" placeholder="请选择降雨量级">
            <el-option v-for="l in levels" :key="l" :label="l + 'mm'" :value="l"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="累计时长">
          <el-select v-model="period" placeholder="请选择量级">
            <el-option v-for="item in periods" :key="item" :label="item + 'h'" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模式">
          <el-checkbox v-for="mode in modes" v-model="mode.isSelected" :key="mode.mode">{{mode.mode}}</el-checkbox>
        </el-form-item>
      </el-form>

      <div class="export-container">
        <div>
          <span>图表导出：</span>
          <el-link class="output" @click="output('PNG')" type="info">PNG</el-link>
          <el-link class="output" @click="output('SVG')" type="info">SVG</el-link>
        </div>
      </div>
    </div>

    <div class="drawing-board" v-loading="chartsLoading">
      <div class="status" v-show="!chartsVisible" @click="drawChart">
        <img :src="imgBrush" height="100">
        <div>
          <span>开始绘制</span>
          <span>start  drawing</span>
        </div>
      </div>

      <div v-show="chartsVisible" :id="chartId" class="chart"></div>
    </div>
  </div>
</template>

<script>
import { pageLoadInfo, skillScores } from "@/api/grapesReps/grapesReps";
import imgBrush from '@/assets/img/brush.svg';
import DatePicker from '@/components/common/DatePicker.vue';

const echarts = require("echarts/lib/echarts");
require("echarts/lib/chart/bar");
require("echarts/lib/chart/line");
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
require("echarts/lib/component/legend");
require("echarts/lib/component/toolbox");
require("echarts/theme/macarons");

function getOption(title, legend, xs, ys) {
  const newYs = [];
  for (let i = 0; i < legend.length; ++i) {
    newYs.push({
      name: legend[i],
      type: 'line',
      data: ys[i],
    })
  }
  return {
    title: {
      subtext: title,
      left: "center",
    },
    tooltip: {},
    // 工具箱内容
    toolbox: {
      itemSize: 20,
      feature: {
        magicType: {
          type: ["line", "bar"],
        },
        dataView: {
          show: true,
          // readOnly: true
        },
      },
    },
    legend: {
      data: legend,
      left: 10,
    },
    // X轴内容
    xAxis: {
      data: xs,
    },
    yAxis: {},
    series: newYs,
    grid: {
      bottom: 40,
      top: 50,
      left: 60,
      right: 30,
    },
  };
}

export default {
  name: "EFCharts",
  components: {
    DatePicker,
  },
  props: {
    timeMode: {
      type: String,
      default: '单日'
    },
    // accu_hour
    periods: {
      type: Array,
      default: () => [1, 3, 6, 12, 24]
    },
    // level
    levels: {
      type: Array,
      default: () => [0.1, 1, 3, 5, 10, 15, 25, 50, 100],
    },
    index: {
      type: Number,
    },
    id: {
      type: Number,
      default: () => new Date().valueOf(),
    },
    showDelete: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      imgBrush,
      // accu_hour
      period: this.periods[0],
      // 日期选择框
      startDate: null,
      endDate: null,
      level: this.levels[0],
      chartsVisible: false,
      chartsLoading: false,
      pageLoading: false,
      page: 'AROC', // 当前页面: BS 或 AROC
      echarts: undefined,
      chartObject: undefined,
      chartOptions: undefined,
      chartTitle: undefined,
      modes: [
        {
          mode: 'grapes_reps',
          dateList: [],
          isSelected: true,
        },
      ],
    }
  },
  methods: {
    pageLoad() {
      this.pageLoading = true;
      pageLoadInfo().then(({data}) => {
        this.modes = data;
      }).finally(() => this.pageLoading = false);
    },
    msg(message, type) {
      this.$message({ message, type });
      return false;
    },
    warning(message) {
      return this.msg(message, 'warning');
    },
    err(message) {
      return this.msg(message, 'error');
    },
    async drawChart() {
      this.chartsVisible = true;
      this.chartsLoading = true;
      const { page: metric, period: accu_hour, startDate: date, endDate, level, multiDay, selectedDateList: dateslist} = this;

      if (accu_hour === 12) {
        this.$message.warning('现业务服务器中无经质量控制的累计12h时长观测数据，无法计算和绘制评分');
        this.chartsVisible = false;
        this.chartsLoading = false;
        return;
      }

      const isDateRange = multiDay ? 1 : 0;
      const mode = this.modes.filter(m => m.isSelected).map(m => m.mode);
      const reqData = {
        metric,
        mode,
        isDateRange,
        date,
        dateslist,
        level,
        accu_hour,
      };

      skillScores(reqData).then(({data}) => {
        let title = '';
        if (this.multiDay)  {
          title = `${metric}_${date}_${endDate}_${level}mm_${accu_hour}h`;
        } else {
          title = `${metric}_${date}_${level}mm_${accu_hour}h`;
        }
        this.chartTitle = title;
        this.chartOption = getOption(title, mode, data.xs, data.ys);
        // console.log(this.chartOption);
        this.$nextTick(() => {
          this.chartObject = echarts.init(document.getElementById(this.chartId), "macarons");
          this.chartObject.setOption(this.chartOption);
        })
      }).finally(() => this.chartsLoading = false);
    },
    output(type) {
      if (!this.chartObject) {
        return this.err('请先绘制图表');
      }
      if (type !== 'PNG' && type !== 'SVG') {
        return this.err(`暂不支持 ${type} 格式`);
      }
      let picInfo = null;
      if (type === "PNG") {
        // 获取到的是一串base64信息
        picInfo = this.chartObject.getDataURL({
          type: "png",
          pixelRatio: 3, // TODO: 需要动态设置比例
          backgroundColor: "#fff",
          excludeComponents: ["toolbox"],
        });
      } else if (type === "SVG") {
        const { clientWidth: width, clientHeight: height} = document.getElementById(this.chartId); // 获取原 dom 的宽高
        let echartContainer = document.createElement("div");
        let echartsInstance = echarts.init(echartContainer, "macarons", {renderer: 'svg'});
        echartsInstance.resize({height, width}); // 设置宽高
        echartsInstance.setOption(this.chartOption);

        // 若使用svg渲染，此处获得的图像数据为svg
        picInfo = echartsInstance.getDataURL({
          type: "png",
          pixelRatio: 1,
          backgroundColor: "#fff",
          excludeComponents: ["toolbox"],
        });
      }

      const elink = document.createElement("a");  // 创建a标签用于下载
      elink.download = this.chartTitle + "." + type;
      elink.style.display = "none";
      elink.href = picInfo;
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);    // 释放URL对象
      document.body.removeChild(elink);   // 移除a标签
    },
    deleteChart() {
      this.$emit('deleteChart', this.index)
    },
  },
  created() {
    this.pageLoad();
  },
  mounted() {
    this.page = this.$route.meta.page.toUpperCase(); // 通过路由确定页面
  },
  computed: {
    multiDay() {
      return this.timeMode === '多日';
    },
    singleDay() {
      return this.timeMode === '单日';
    },
    chartId() {
      return 'chart-' + this.id;
    },
    dateOptions() {
      const selectedModes = this.modes.filter(mode => mode.isSelected);
      if (selectedModes.length === 0) {
        return [];
      }
      let resultSet = new Set(selectedModes[0].dateList);
      for (let i = 1; i < selectedModes.length; ++i) {
        resultSet = new Set(selectedModes[i].dateList.filter(date => resultSet.has(date)));
      }
      return [...resultSet];
    },
    selectedDateList() {
      const {startDate, endDate} = this;
      const startIndex = this.dateOptions.indexOf(startDate);
      const endIndex = this.dateOptions.indexOf(endDate);
      if (startIndex === -1 || endIndex === -1) {
        return [];
      }
      return this.dateOptions.slice(startIndex, endIndex + 1);
    }
  },
  watch: {
    dateOptions () {
      if (this.dateOptions.length === 0 ) {
        return;
      }
      this.startDate = this.dateOptions[0];
      this.endDate = this.dateOptions[this.dateOptions.length - 1];
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/main.scss';
@import '@/assets/css/EFcontent.scss';

.content-container{
  .content{
    width: 100%;
    overflow: auto;
    top: 45px;
  }
}

.main {
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 40px 40px 0px;
  .option-container {
    width: 100%;
    display: flex;
    justify-content: space-between;
    form {
      flex: 1;
    }
  }

  .export-container {
    .output{
      padding: 0 5px;
    }
  }

  .drawing-board {
    width: 100%;
    height: 410px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    margin: 10px 0;
    @include flex-center();

    .chart {
      height: 100%;
      width: 100%;
    }

    .status {
      height: 100px;
      width: 200px;
      display: flex;
      cursor: pointer;
      div {
        flex: 1;
        @include flex-center();
        flex-direction: column;
        span:first-child {
          font-size: 20px;
          font-weight: 500;
          color: #666666;
          margin-bottom: 10px;
        }
        span:last-child {
          color: #CCCCCC;
        }
      }
    }
  }
}
</style>